package zju.ccnt.rest.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zju.ccnt.rest.api.ApiEndUser;
import zju.ccnt.rest.domain.EndUser;
import zju.ccnt.rest.repository.EndUserRepository;
import zju.ccnt.oauth2.user.UserService;
import zju.ccnt.oauth2.user.api.CreateUserRequest;
import zju.ccnt.oauth2.user.api.PasswordRequest;
import zju.ccnt.oauth2.user.exception.DuplicateUserException;
import zju.ccnt.oauth2.user.exception.InvalidUserException;

/**
 * Created by zha on 14/11/6.
 */
@Service
public class EndUserServiceImpl extends UserService<ApiEndUser> {
    private Logger LOG = LoggerFactory.getLogger(EndUserServiceImpl.class);
    private EndUserRepository endUserRepository;

    @Autowired
    public EndUserServiceImpl(EndUserRepository endUserRepository) {
        super();
        this.endUserRepository = endUserRepository;
    }

    @Override
    public void updateUserPasswordToDB(PasswordRequest newPassword, String email) {
        LOG.info("update end_user[{}] password.", email);
        EndUser endUser = endUserRepository.findByEmail(email);
        if (endUser != null) {
            endUser.setPassword(passwordEncoder.encode(newPassword.getPassword()));
            endUserRepository.save(endUser);
        } else {
            LOG.info("No valid end_user email was given");
            throw new InvalidUserException(email);
        }
    }

    @Override
    public ApiEndUser getUser(String email) {
        return null;
    }

    @Override
    public ApiEndUser createUserToDB(CreateUserRequest<ApiEndUser> createUserRequest) {
        LOG.info("Validating end_user request.");
        //validate(request);
        final String email = createUserRequest.getUser().getEmail();
        if (endUserRepository.findByEmail(email) == null) {
            LOG.info("EndUser does not already exist in the data store - creating a new user [{}].", email);
            EndUser newUser = new EndUser(createUserRequest.getUser(),passwordEncoder.encode(createUserRequest.getPassword().getPassword()));
            endUserRepository.save(newUser);
            LOG.debug("Created new user [{}] ", newUser.getName() + "@" + newUser.getName());
            return new ApiEndUser(newUser);
        } else {
            LOG.info("Duplicate user located, exception raised with appropriate HTTP response code.");
            throw new DuplicateUserException(email);
        }
    }
}
